/*-----------------------------------------------------------------------------
 * @file   hal_hrt.c
 * @brief  Interface for High-resolution timer (USE REG_DWT_CYCCNT)
 * @author WLH<wanglehui8357@163.com> Copyright (C) 2021~2099.
-----------------------------------------------------------------------------*/
#include "hal_hrt.h"
#include "hal_irq.h"
#include "board.h"

/*-----------------------------------------------------------------------------
 * High-resolution timer, unit: 1 us =  1/1000 ms
-----------------------------------------------------------------------------*/
#define TICK_CNT_TO_US(a) ((a)*1000UL*1000UL/SystemCoreClock)

/*-----------------------------------------------------------------------------
 * local variable
-----------------------------------------------------------------------------*/
extern uint32_t get_sys_tick(void);

/*-----------------------------------------------------------------------------
 * public functions
-----------------------------------------------------------------------------*/
void hal_hrt_init(void)
{
    /* Enable Cortex-M4/7 DWT CYCCNT reg. */
}

/**
 * Fetch a never-wrapping absolute time value in microseconds from
 * some arbitrary epoch shortly after system start.
 */
hrt_abstime hal_hrt_get_us(void)
{
    vU32 raw_tick  = (SystemCoreClock / 1000U) - SysTick->VAL;
    return get_sys_tick() * 1000u + TICK_CNT_TO_US(raw_tick);
}

hrt_abstime hal_hrt_elapsed_us(const hrt_abstime then)
{
    hrt_abstime curr_us = hal_hrt_get_us();
    return curr_us - then;
}

U32 hal_hrt_get_ms(void)
{
    /* get _tx_timer_system_clock by API */
    return get_sys_tick();
}

U32 hal_hrt_elapsed_ms(const U32 then)
{
    return get_sys_tick() - then;
}
